import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex);

export default new Vuex.Store({
    state:{
        todos:[]
    },
    mutations:{ //同步
        getTodosSync(state,arr){
            state.todos = arr
        },
        addTodosSync(state,todo){
            state.todos.push(todo)
        },
        delSync(state,id){
            let index = state.todos.findIndex(item => item.id === id);
            state.todos.splice(index,1);
        },
        editSync(state,todo){
            let index = state.todos.findIndex(item => item.id === todo.id);
            state.todos[index].done = !todo.done;
        }
    },
    getters:{
        activeCount(state){
            return state.todos.filter(item => !item.done).length
        }
    },
    actions:{ //异步
        getTodos({commit}){
            axios.get('/api/todos').then(res => {
                if(res.data.code === 1){
                    commit('getTodosSync',res.data.data)
                }
            })
        },
        addTodos({commit},text){
            let id = new Date().getTime();
            axios.post('/api/add',{text,done:false,id}).then(res => {
                if(res.data.code === 1){
                    commit('addTodosSync',{text,done:false,id})
                }
            })
        },
        del({commit},id){
            console.log("======")
            axios.get(`/api/del?id=${id}`).then(res => {
                if(res.data.code === 1){
                    commit('delSync',id)
                }
            })
        },
        editTodo({commit},todo){
            axios.get(`/api/edit?id=${todo.id}&done=${todo.done}`).then(res => {
                if(res.data.code === 1){
                    commit('editSync',todo)
                }
            })
        },
        toggleAll({commit,state},checkAll){
            axios.get(`/api/toggle?done=${checkAll}`).then(res => {
                if(res.data.code === 1){
                     state.todos.forEach(item => {
                        commit('editSync',item)
                     })
                }
            })
        }
    }
})